package com.allwees.bs.core.modelbase.page;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import javax.validation.constraints.Max;
import java.io.Serializable;

/**
 * 翻页参数 可直接注入到controller中
 */
@Data
public class PageParams implements Serializable {

	private static final long serialVersionUID = 6030663737620366889L;

	private Integer current = 1;

	@Max(value = 100,message = "Maximum of 100 per page~")
	private Integer size = 20;

	public PageParams() {
	}

	public PageParams(int current, int size) {
		this(current, size, 50);
	}

	public PageParams(int current, int size, Integer max) {
		this.current = current;
		this.current = this.current < 1 ? 1 : this.current;

		this.size = size;
		this.size = this.size <= 0 ? 20 : (this.size > max ? max : this.size);
	}

	public static PageParams of(int current, int size) {
		return new PageParams(current, size);
	}

	public static PageParams of(String current, String size) {
		int pageV = StringUtils.isNumeric(current) ? Integer.parseInt(current) : 1;
		int sizeV = StringUtils.isNumeric(size) ? Integer.parseInt(size) : 20;
		return new PageParams(pageV, sizeV);
	}

	public Pageable toPageable() {
		return PageRequest.of(this.current - 1, this.size);
	}

	public Pageable toPageable(Sort.Direction direction, String... properties) {
		return PageRequest.of(this.current - 1, this.size, Sort.by(direction, properties));
	}

	public <T> Page<T> toPage() {
		return new Page<>(current, size);
	}
}
